package com.lzx.adx.report.controller.v1.common;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.redis.RedisUtils;
import com.lzs.adx.commmon.utils.DateUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.biz.IpService;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.constant.RedisKeyConstant;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.ViVoData;
import com.lzx.adx.report.model.vivo.ViVoRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.DynamicRequestLimiter;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.service.AccountService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonCtroller {


    @Autowired
    private AccountService accountService;



    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DynamicRequestLimiter dynamicRequestLimiter;

    @Autowired
    private ReportService reportService;

    @Autowired
    private IpService ipService;


    @ApiOperation("同步数据库到缓存")
    @GetMapping("sysnCacheToDb")
    public Result sysnCacheToDb(){
        //1.查询所有的账号信息
        accountService.sysnCacheToDb();
        //2.查看缓存的内容
        return this.getCacheInfo();
    }


    @RequestMapping("/ag")
    public Result avg(){
        String total="a";
        String proce="b";


        if (dynamicRequestLimiter.shouldProcessRequest(total, proce, 0.25)) {
            System.out.println("Processing request: " );
        } else {
            System.out.println("Dropping request: " );
        }

        return new Result();
    }




    @ApiOperation("查询缓存信息")
    @GetMapping("getCacheInfo")
    public Result getCacheInfo(){
        String allJsonData = AccountLocalCache.getInstance().getAllJsonData();
        ConcurrentMap<String,AccountDTO> resultMap=JsonUtils.parseObject(allJsonData, ConcurrentHashMap.class);
        return new Result().ok(resultMap);
    }


    @ApiOperation("清理所有缓存")
    @GetMapping("cleanAllData")
    public Result cleanAllData(){
        AccountLocalCache.getInstance().cleanAllData();
        return this.getCacheInfo();
    }

    @GetMapping("ip")
    public Result getIp(String ip){
        return new Result().ok(ipService.getRegion(ip));
    }


    @ApiOperation("获取快分佣命中的数据")
    @GetMapping("getKfyData")
    public Result getKfyData(){
        Map<String, Object> stringObjectMap = redisUtils.hgetAll(RedisKeyConstant.HW_KFY);
        return new Result().ok(stringObjectMap);
    }


    @ApiOperation("获取快分佣命中的数据")
    @GetMapping("deleteALlKfyData")
    public Result deleteALlKfyData(){
        redisUtils.delete(RedisKeyConstant.HW_KFY);
        return new Result().ok();
    }




    @ApiOperation("获取趣头条-西瓜视频数据")
    @GetMapping("getQttXgspData")
    public Result getQttXgspData(){
        Map<String, Object> stringObjectMap = redisUtils.hgetAll(RedisKeyConstant.QTT_XGSP);
        return new Result().ok(stringObjectMap);
    }


    @ApiOperation("删除趣头条-西瓜视频数据")
    @GetMapping("deleteQttXgspData")
    public Result deleteQttXgspData(){
        redisUtils.delete(RedisKeyConstant.QTT_XGSP);
        return new Result().ok();
    }


    @RequestMapping("fix")
    public void fixVivoYyData(){
        List<String> strings = FileUtil.readLines(new File("E://a.txt"), StandardCharsets.UTF_8);
        List<Map<String, String>> maps = extractDateAndTransactionId(strings);
        for (Map<String, String> map : maps) {
            String date = map.get("date");
            String id = map.get("id");

            Date parse = DateUtils.parse(date, DateUtils.DATE_PATTERN);
            callback(id,"7",String.valueOf(parse.getTime()));
        }

    }


    public ResponseEntity<?> callback(String requestId, String transformType,String event_time) {
        log.info("vivo接收了优优-天猫拉活回调信息请求流水号{},回调类型为{}", requestId, transformType);
        if (StringUtils.isBlank(requestId)||StringUtils.isBlank(transformType)) {
            log.info("vivo接收了优优-天猫拉活回调信息参数异常");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.将结果上报给VIVO
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String code = jsonObject.getString(transformType);
        if (StringUtils.isBlank(code)){
            log.info("vivo接收了优优-天猫拉活回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId,transformType);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(transformType);
        reportDTO.setResultTime(event_time);
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,transformType);
        ViVoRequest viVoRequest = JSONObject.parseObject(reportDTO.getExtend(), ViVoRequest.class);
        ViVoData viVoData = new ViVoData();
        viVoData.setCvTime(event_time);
        viVoData.setCvType(code);
        viVoData.setRequestId(viVoRequest.getRequestId());
        viVoData.setCreativeId(viVoRequest.getContentId());
        if ("PAY".equals(code)){
            ViVoData.ExtParam extParam=new ViVoData.ExtParam();
            viVoData.setExtParam(extParam);
        }
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("srcType","WEB");
        paramsMap.put("pageUrl",jsonObject.getString("pageUrl"));
        paramsMap.put("srcId",jsonObject.getString("srcId"));
        paramsMap.put("dataList", Lists.newArrayList(viVoData));
        String resultPams = JSON.toJSONString(paramsMap);
        String url = accountDTO.getSspApiUrl() + "?access_token=" + accountDTO.getSspKey() + "&timestamp=" + event_time + "&nonce=" + IdUtil.fastSimpleUUID() + "&advertiser_id=" + viVoRequest.getAccountId();
        log.info("账号{}，请求id{}优优-天猫拉活给vivo请求地址为地址为：{}，请求参数为{}", reportDTO.getDspId(), requestId, url, resultPams);
        String post = HttpUtil.post(url, resultPams);
        log.info("账号{}，请求id{}优优-天猫拉活给vivo请求转换响应的结果为：{}", reportDTO.getDspId(), requestId, post);
        return ResponseEntity.ok(new Result());
    }


    public static  List<Map<String, String>> extractDateAndTransactionId(List<String> list) {
        List<Map<String, String>> lists = new ArrayList<>();
        for (String logLine : list) {
            // 正则表达式，用于匹配日期和流水号
            String regex = "(\\d{4}-\\d{2}-\\d{2})\\s+.*?当前流水号：([a-f0-9]+)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(logLine);
            Map<String, String> stringStringMap = new HashMap<>();
            if (matcher.find()) {
                stringStringMap.put("date", matcher.group(1));
                stringStringMap.put("id", matcher.group(2));
            }
            lists.add(stringStringMap);
        }
        return lists;
    }

}
